package org.m2acsi.boundary;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public abstract class BaseEJB<T> {

    protected final Class<T> entityClass;

    public BaseEJB(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public void save(T entity) {
        em().persist(entity);
    }

    public T update(T entity) {
        return em().merge(entity);
    }

    public abstract void remove(T entity);

    public abstract EntityManager em();

    public T find(long id) {
        return em().find(entityClass, id);
    }

    public List<T> findAll() {
        CriteriaBuilder builder = em().getCriteriaBuilder();
        CriteriaQuery<T> criteria = builder.createQuery(entityClass);
        Root<T> root = criteria.from(entityClass);
        criteria.select(root);
        return em().createQuery(criteria).getResultList();
    }
}
